package cn.jiangjiesheng.bootstrap.fileport.interfaces;

import cn.jiangjiesheng.bootstrap.commons.exception.BizzException;
import cn.jiangjiesheng.bootstrap.fileport.domain.doc.PdfConverterDo;
import cn.jiangjiesheng.bootstrap.fileport.domain.doc.WordTemplateReader;
import cn.jiangjiesheng.bootstrap.fileport.interfaces.model.DocDataModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * Created by dev@jiangjiesheng.cn on 2021/3/17  <br/>
 * @author jerrylau
 */
@Slf4j
public class DocExporter {

    private InputStream template;

    private DocDataModel docDataModel;

    /**
     * 生成报告
     *
     */
    public InputStream build()  {
        if(Objects.isNull(template)){
            throw new BizzException("未设置模块，调用 setTemplate设置");
        }
        if(Objects.isNull(docDataModel)){
            throw new BizzException("未设置输入数据，调用setDocDataModel设置");
        }
        return new WordTemplateReader(template, docDataModel).toInputStream();
    }

    /**
     * 创建临时文件
     *
     * @return File
     */
    public File buildTemporaryFile() {
        File outTempFile = null;
        InputStream inputStream = build();
        try {
            outTempFile = File.createTempFile("fileport_",".docx");
            FileUtils.copyInputStreamToFile(inputStream,outTempFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outTempFile;
    }

    public InputStream buildInputStream(){
        return build();
    }

    /**
     * 将报告转为pdf版本
     *
     * @return
     * @throws IOException
     */
    public File buildPdf()  {
        File temporaryFile = null;
        try {
            temporaryFile = File.createTempFile("fileport-",".pdf");
            InputStream inputStream = new ByteArrayInputStream(new PdfConverterDo(build()).toBytes());
            FileUtils.copyInputStreamToFile(inputStream,temporaryFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return temporaryFile;
    }

    public DocExporter setTemplate(InputStream template) {
        this.template = template;
        return this;
    }

    public DocExporter setDocDataModel(DocDataModel docDataModel) {
        this.docDataModel = docDataModel;
        return this;
    }
}
